package bootload

import (
	"cabinet/pkg/global"
	"fmt"
	mqtt "github.com/eclipse/paho.mqtt.golang"
	"log"
	"time"
)

var Client mqtt.Client

type MessageHandler func(topic string, payload []byte)

func InitEMQXClient() {

	//// 初始化MQTT客户端
	//mqttClient, err := util.NewMQTTClient("tcp://localhost:1883", "cabinet-server")
	//if err != nil {
	//	log.Fatal("Failed to connect to MQTT broker:", err)
	//}
	//defer mqttClient.Close()

	//opts := mqtt.NewClientOptions().AddBroker("tcp://localhost:1883")        "tcp://broker.emqx.io:1883"
	opts := mqtt.NewClientOptions().AddBroker("tcp://broker.emqx.io:1883").SetClientID(global.Conf.MQTT.ClientID)
	//opts.AddBroker(fmt.Sprintf("tcp://%s:%d", global.Conf.MQTT.Broker, global.Conf.MQTT.Port))
	opts.SetUsername(global.Conf.MQTT.Username)
	opts.SetPassword(global.Conf.MQTT.Password)
	//配置重连逻辑
	opts.SetAutoReconnect(true)
	opts.SetMaxReconnectInterval(10 * time.Second)
	opts.OnConnectionLost = func(c mqtt.Client, err error) {
		log.Printf("MQTT 连接丢失: %v", err)
	}
	opts.OnReconnecting = func(c mqtt.Client, co *mqtt.ClientOptions) {
		log.Printf("尝试重连EMQX...")
	}
	Client = mqtt.NewClient(opts)
	if token := Client.Connect(); token.Wait() && token.Error() != nil {
		panic(fmt.Sprintf("MQTT连接失败: %v", token.Error()))
	}
}

// 订阅主题
func Subscribe(topic string, handler MessageHandler) {
	if token := Client.Subscribe(topic, 0, func(client mqtt.Client, message mqtt.Message) {
		handler(message.Topic(), message.Payload())
	}); token.Wait() && token.Error() != nil {
		panic(fmt.Sprintf("订阅主题失败: %v", token.Error()))
	}
}

// 发布消息
func Publish(topic string, payload interface{}) error {
	token := Client.Publish(topic, 1, false, payload)
	token.Wait()
	return token.Error()
}
